package com.glsc.ngateway.opmanage.service.report.excel.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.metadata.Cell;
import com.alibaba.excel.read.metadata.holder.ReadRowHolder;
import com.alibaba.excel.read.metadata.holder.ReadSheetHolder;
import com.glsc.ngateway.common.base.domain.mysql.opmanage.report.fileupload.ImportTemplateRulesDefine;
import com.glsc.ngateway.common.base.dto.opmanage.report.DerivativeException;
import org.springframework.util.CollectionUtils;

import java.text.MessageFormat;
import java.util.Arrays;
import java.util.List;
import java.util.Locale;

/**
 * @author: qiyr
 * @date: 2022/8/10 10:24
 * @description: 导入文件模板格式校验处理
 */
public class TemplateCheckHandler {

    private static final String SEPARATE = ";";
    private static final String ERROR_MSG = "导入失败，第{0}个sheet页：''{1}''中，第{2}行{3}列内容应为：{4}，请检查文件模板格式";

    public static void check(AnalysisContext context, List<ImportTemplateRulesDefine> rulesDefineList) {
        if (CollectionUtils.isEmpty(rulesDefineList)) {
            return;
        }
        ReadRowHolder readRowHolder = context.readRowHolder();
        ReadSheetHolder readSheetHolder = context.readSheetHolder();

        for (ImportTemplateRulesDefine define : rulesDefineList) {
            String[] positions = define.getPosition().split(SEPARATE);
            Integer row = Integer.parseInt(positions[0]);
            if (!readRowHolder.getRowIndex().equals(row - 1)) {
                continue;
            }
            Integer column = getColumn(positions[1].toUpperCase(Locale.ROOT));
            List<String> content = Arrays.asList(define.getContent().split(SEPARATE));
            Cell cell = readRowHolder.getCellMap().get(column - 1);
            if (cell == null || !content.contains(handleCellString(cell.toString()))) {
                throw DerivativeException.error(MessageFormat.format(ERROR_MSG,
                        readSheetHolder.getSheetNo() + 1, readSheetHolder.getSheetName(), row, positions[1], content));
            }
        }
    }

    // 一位数表示26列以内，直接取ASCII码计算
    // 两位数表示需要使用字母组合计算，首字母表示轮次，尾字母表示序号，如AA表示27(1*26+1)
    private static Integer getColumn(String columnString) {
        int column = Integer.valueOf(columnString.getBytes()[0]) - 64;
        if (columnString.length() == 1) {
            return column;
        } else if (columnString.length() == 2) {
            int index = Integer.valueOf(columnString.getBytes()[1]) - 64;
            return column * 26 + index;
        } else {
            throw new RuntimeException("文件模板校验规则解析失败，行列配置异常");
        }
    }

    private static String handleCellString(String cellString) {
        return cellString.trim().replace("\r", "").replace("\n", "").
                replace("\t", "").replace(" ", "");
    }

}
